/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

// 网点小程序管理

import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import DragTable from '@/components/DragTable';
import { getAccountsList, WeiXinMpCustom } from '@/services/networkWxmini';
import { Button, Form, Input, message, Radio, Space } from 'antd';
import KbPopconfirm from '@/components/KbPopconfirm';
import ProForm, {
  DrawerForm,
  ProFormText,
  ProFormSelect,
  ProFormDateRangePicker,
  ProFormDateTimePicker,
  ModalForm,
} from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import { history, useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import { isArray } from 'lodash';
import dataParam from './types/config';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { Kbdby } from './index.d';
import styles from './index.less';

interface renderParam {
  label: string;
  children: [];
  map: any;
}

interface TypeCurrentData {
  platform: string;
  app_label: string;
}
interface TypeInterworkingData {
  platform: string;
  nick_name: string;
}

const Administrators: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const formRef1 = useRef<ProFormInstance>();
  const formRef2 = useRef<ProFormInstance>();
  const formRef3 = useRef<ProFormInstance>();
  const formRef4 = useRef<ProFormInstance>();
  const formRef5 = useRef<ProFormInstance>();
  const formRef6 = useRef<ProFormInstance>();
  const secrchOption = [
    { value: '', label: '全部' },
    { value: '0', label: '开启' },
    { value: '1', label: '关闭' },
  ];
  const titles = {
    jurisdiction: '权限管理',
    edit: '编辑',
    deploy: '部署小程序',
    Interworking: '数据互通',
  };

  const [version, setVersion] = useState('2');
  const [choiceData, setChoiceData] = useState({});
  const [radioType, setRadioType] = useState('0');
  const [editionList, setEditionList] = useState([]);
  const [options, setOptions] = useState('');
  const [drawerTitle, setDrawerTitle] = useState('');
  const [renderParam, setRenderParam] = useState([]);
  const [modalVisit, setModalVisit] = useState(false);
  const [drawerVisit, setDrawerVisit] = useState(false);
  const [currentData, setCurrentData] = useState({} as TypeCurrentData);
  const [interworkingData, setInterworkingData] = useState({} as TypeInterworkingData);
  const [searchData, setSearchData] = useState({});

  const setInitialValues = async (params: any) => {
    const callback = params.cb;
    getAccountsList(params).then((data) => {
      const { auth_time, auth_cancel_time, ...rest } = data;
      if (!auth_time) {
        rest.auth_cancel_time = auth_cancel_time;
      } else if (!auth_cancel_time) {
        rest.auth_time = auth_time;
      }
      formRef6.current?.setFieldsValue(rest);
    });
    if (typeof callback === 'function') {
      callback();
    }
    return true;
  };

  const onAuthority = (params: any, index: any) => {
    const { platform, platform_type } = params;
    if (index === 'administrators') {
      history.push({
        pathname: '/f/wechat/mini/admin',
        query: {
          open_platform: platform,
          platform_type,
        },
      });
      return;
    }
    if (index === 'adInfo') {
      history.push({
        pathname: '/f/wechat/mini/ad',
        query: {
          platform,
          platform_type,
        },
      });
      return;
    }
    const action = {
      jurisdiction: 'authInfo',
      edit: 'authOfficialAccountsGet',
    };
    setCurrentData(params);
    setOptions(index);
    setRenderParam(dataParam[index]);
    setDrawerTitle(titles[index]);
    setDrawerVisit(true);
    setInitialValues({ action: action[index], platform: params.platform });
  };

  const tableReload = () => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (!reset) return;
    reset();
  };

  const confirm = (values: any) => {
    const { platform } = values;
    setInitialValues({
      action: 'changeCloseStatus',
      platform,
      cb: () => {
        tableReload();
      },
    });
  };

  const onVisibleChange = (params: any, index: any) => {
    if (index === 'deploy' && params.is_newbest == '1') {
      message.info('当前已是最新版本');
      return;
    }
    if (index === 'Interworking') {
      setInterworkingData({} as TypeInterworkingData);
    }
    setCurrentData(params);
    setRadioType(`${params.current_version}`);
    setChoiceData(params);
    setDrawerTitle(titles[index]);
    setModalVisit(true);
    setOptions(index);
  };

  const WeiXinMpCustoms = (params: any, action: any = 'singleDeploy') => {
    WeiXinMpCustom({ ...params, action }).then((res) => {
      if (res.code == 0) {
        tableReload();
        setModalVisit(false);
      }
      message.info(res.msg);
    });
  };

  const columns: ProColumns<Kbdby>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      search: false,
      width: 80,
      ellipsis: true,
      render: (_, __, index) => index + 1,
    },
    {
      title: '平台标识',
      dataIndex: 'platform',
      align: 'center',
      search: false,
      width: 120,
      ellipsis: true,
    },
    {
      title: '名称',
      dataIndex: 'nick_name',
      align: 'center',
      search: false,
      width: 200,
      ellipsis: true,
    },
    {
      title: 'AppId',
      dataIndex: 'auth_app_id',
      align: 'center',
      search: false,
      width: 120,
      ellipsis: true,
    },
    {
      title: '用户信息',
      dataIndex: 'user_info',
      align: 'center',
      search: false,
      width: 250,
      ellipsis: true,
      render: (_, r) => {
        const { user_info = {} } = r;
        const allUser = user_info.name || user_info.phone;
        return `${
          allUser
            ? `${user_info.name ? user_info.name : ''} ${user_info.phone ? user_info.phone : ''}`
            : '-'
        }`;
      },
    },
    {
      title: '加盟商（是/否）',
      dataIndex: 'is_franchisee',
      align: 'center',
      search: false,
      width: 120,
      ellipsis: true,
      render: (_, r) => (r.is_franchisee == '1' ? '是' : '否'),
    },
    {
      title: '实属加盟商',
      dataIndex: 'franchisee_info',
      align: 'center',
      search: false,
      width: 250,
      ellipsis: true,
    },
    {
      title: '版本类型',
      dataIndex: 'version_type',
      align: 'center',
      search: false,
      width: 120,
      ellipsis: true,
      render: (obj, r: any) => {
        const { version_type, version_code } = r;
        const versionMap: any = {
          P: '快递版',
          N: '普通版',
          C: '插件版',
        };
        return versionMap[version_type] ? `${versionMap[version_type]}${version_code}` : '-';
      },
    },
    {
      title: '级别',
      dataIndex: 'level',
      align: 'center',
      search: false,
      width: 80,
      ellipsis: true,
      render: (level, r: any) => {
        return r.level == '1' ? '个人' : r.level == '2' ? '企业' : '未知';
      },
    },
    {
      title: '开始服务时间',
      dataIndex: 'auth_time',
      align: 'center',
      search: false,
      width: 200,
      ellipsis: true,
    },
    {
      title: '结束服务时间',
      dataIndex: 'auth_cancel_time',
      align: 'center',
      search: false,
      width: 200,
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      valueType: 'option',
      dataIndex: 'option',
      width: winSize === 'xs' ? 100 : 200,
      fixed: 'right',
      render: (_, record: any) => {
        return (
          <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
            <a onClick={() => onAuthority(record, 'edit')}>编辑</a>
            <a onClick={() => onAuthority(record, 'jurisdiction')}>权限管理</a>
            <a onClick={() => onAuthority(record, 'administrators')}>管理员</a>
            <a onClick={() => onAuthority(record, 'adInfo')}>广告位</a>
            {record.is_company === '0'
              ? [
                  <KbPopconfirm
                    text={`您确定${
                      record.is_close == '0' ? '关闭' : record.is_close == '1' ? '开启' : ''
                    }此小程序吗？`}
                    confirm={() => confirm(record)}
                    okText='确定'
                    cancelText='取消'
                    key={record.id}
                  >
                    <a>
                      {`${record.is_close == '0' ? '关闭' : record.is_close == '1' ? '开启' : ''}`}
                      服务
                    </a>
                  </KbPopconfirm>,
                  [
                    record.is_history === '0'
                      ? [
                          [
                            !record.version_code
                              ? [
                                  <a onClick={() => onVisibleChange(record, 'deploy')}>
                                    部署小程序
                                  </a>,
                                ]
                              : [
                                  record.version_type === 'N' ? (
                                    <KbPopconfirm
                                      text='确定将小程序进行版本升级？'
                                      confirm={() =>
                                        WeiXinMpCustoms({
                                          edition_id: '2',
                                          auth_app_id: record.auth_app_id,
                                        })
                                      }
                                      cancel={() => {}}
                                      okText='确定'
                                      cancelText='取消'
                                      key={record.id}
                                    >
                                      <Button
                                        size='small'
                                        disabled={record.is_audit === '2'}
                                        key='pay'
                                        type='primary'
                                      >
                                        {record.is_audit === '2' ? '审核中' : '升级快递版'}
                                      </Button>
                                    </KbPopconfirm>
                                  ) : null,
                                ],
                          ],
                          [
                            record.version_code ? (
                              <Button
                                key='pay'
                                size='small'
                                disabled={record.is_audit === '2'}
                                onClick={() => onVisibleChange(record, 'deploy')}
                                type='primary'
                              >
                                {record.is_audit === '2' ? '审核中' : '升级版本号'}
                              </Button>
                            ) : null,
                          ],
                          <Button
                            key='pay'
                            size='small'
                            disabled={record.is_interflow === '1'}
                            onClick={() => onVisibleChange(record, 'Interworking')}
                            type='primary'
                          >
                            {record.is_interflow === '0'
                              ? '数据互通'
                              : record.is_interflow === '1'
                              ? '已互通'
                              : null}
                          </Button>,
                        ]
                      : null,
                  ],
                ]
              : null}
          </Space>
        );
      },
    },
  ];

  const fetchTableList = (params: any, searchData_: any) => {
    const { current: page, pageSize } = params;
    return getAccountsList({
      action: 'authOfficialAccountsList',
      mini_type: version,
      page_num: page,
      page_size: pageSize,
      ...searchData_,
      type: 2, // 1公众号 2小程序
    });
  };

  const onSubmit = async (values: any, searchData_: any) => {
    if (isArray(values.search_key)) {
      const [start_time, over_time] = values.search_key;
      values = {
        type: 2,
        ...values,
        start_time,
        over_time,
        ...searchData_,
      };
      delete values.search_key;
    }
    setSearchData({ ...values, ...searchData_ });
    tableReload();
    return true;
  };

  const onSearch = (values_: any, _: any, action: any) => {
    if (!values_) {
      message.info('输入互通公众号平台标识');
      return;
    }
    getAccountsList({
      action,
      gzh_platform: values_,
    }).then((data) => {
      if (!data) return;
      setInterworkingData(data);
    });
  };

  const upgradeAll = (editionList_: any) => {
    if (editionList_.length <= 0) {
      message.info('批量打印最少选择一条');
      return;
    }
    WeiXinMpCustoms({ data: JSON.stringify(editionList_) }, 'batchDeploy');
  };

  const selectiChange = (selectedRowKeys: any, selectedRows: any) => {
    const selectKeys = selectedRows.map((item: any) => item.auth_app_id);
    setEditionList(selectKeys);
  };

  const onRadioChange = (e: any) => {
    const { value } = e.target;
    setRadioType(value);
  };

  const modalSubmit = async (
    _: any,
    radioType_: any,
    choiceData_: any,
    interworkingData_: any,
    options_: any,
  ) => {
    if (options_ === 'Interworking') {
      if (!interworkingData_.platform) {
        message.info('未获取到对应的公众号信息');
        return false;
      }
      getAccountsList({
        action: 'interflowData',
        gzh_platform: interworkingData_.platform,
        mini_platform: choiceData_.platform,
      }).then((res) => {
        if (res.code == 0) {
          setModalVisit(false);
          tableReload();
        }
        message.info(res.msg);
      });
      return false;
    }
    const { auth_app_id } = choiceData_;
    const radioArr = [
      {
        edition_id: '1',
        company_level: '1',
      },
      {
        edition_id: '1',
        company_level: '2',
      },
      {
        edition_id: '2',
      },
    ];
    WeiXinMpCustoms({ ...radioArr[Number(radioType_) - 1], auth_app_id });
    return true;
  };

  const choiceVersion = (e: any) => {
    const { value } = e.target;
    setVersion(value);
    formRef4.current?.setFieldsValue({ status: '' });
    onSubmit({}, { ...searchData, mini_type: value });
  };

  const onReload = async (version_: any) => {
    await formRef2.current?.resetFields();
    await formRef3.current?.resetFields();
    await formRef4.current?.resetFields();
    onSubmit({ mini_type: version_ }, {});
    return true;
  };

  const { Search } = Input;
  return (
    <PageContainer className={styles.main} title=''>
      <Space direction='vertical' className={styles.space}>
        <ProForm formRef={formRef1} layout='inline' submitter={false}>
          <Form.Item label='版本'>
            <Radio.Group
              defaultValue={version}
              name='type'
              onChange={choiceVersion}
              buttonStyle='solid'
            >
              <Radio.Button value='2'>定制小程序</Radio.Button>
              <Radio.Button value='1'>历史小程序</Radio.Button>
            </Radio.Group>
          </Form.Item>
          {/* <ProFormSelect options={[{label: '历史小程序', value: '1'}, {label: '定制小程序', value: '2'}]} initialValue="1" width="sm" name="type" label="版本" /> */}
        </ProForm>
        <Space direction={winSize === 'xs' ? 'vertical' : 'horizontal'}>
          <ProForm
            formRef={formRef2}
            layout='inline'
            onFinish={(values) => onSubmit({ ...values, mini_type: version }, {})}
            submitter={{
              render: (props) => {
                return [
                  <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormText
              name='search_key'
              width='md'
              placeholder='请输入名称/平台标识/appid进行搜索'
            />
          </ProForm>
          <ProForm
            formRef={formRef3}
            layout='inline'
            onFinish={(values) => onSubmit({ ...values, mini_type: version }, {})}
            // initialValues={{
            //   search_key: [start_time, over_time]
            // }}
            submitter={{
              render: (props) => {
                return [
                  <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormDateRangePicker name='search_key' width='md' />
          </ProForm>
          <ProForm
            formRef={formRef4}
            layout='inline'
            onFinish={(values) => onSubmit({ ...values, mini_type: version }, {})}
            initialValues={{
              status: '',
            }}
            submitter={{
              render: (props) => {
                return [
                  <Button type='primary' key='submit' onClick={() => props.form?.submit?.()}>
                    搜索
                  </Button>,
                ];
              },
            }}
          >
            <ProFormSelect
              options={secrchOption}
              width='md'
              name='status'
              placeholder='请选择服务状态'
            />
          </ProForm>
          <Button
            onClick={() => {
              onReload(version);
            }}
          >
            重置
          </Button>
          <KbPopconfirm
            text='确定将选中小程序进行版本升级？'
            confirm={() => upgradeAll(editionList)}
            cancel={() => {}}
            okText='确定'
            cancelText='取消'
          >
            <Button type='primary'>批量升级版本</Button>
          </KbPopconfirm>
        </Space>
      </Space>
      <DrawerForm
        title={drawerTitle}
        visible={drawerVisit}
        formRef={formRef6}
        onVisibleChange={setDrawerVisit}
        onFinish={(values) =>
          setInitialValues({
            action: options == 'edit' ? 'authOfficialAccountsEdit' : 'editAuthInfo',
            ...values,
            platform: currentData.platform,
            cb: () => tableReload(),
          })
        }
        width={winSize === 'xs' ? 300 : 800}
      >
        {renderParam.map((key: renderParam, index0: number) => {
          return (
            <div key={index0}>
              <div>
                <h2>{key.label}</h2>
                {options === 'jurisdiction' || options === 'edit' ? (
                  <ProForm.Group>
                    {key.children.map(
                      (
                        item: {
                          name: string;
                          label: string;
                          placeholder: string;
                          disabled: boolean;
                          isSelect: boolean;
                          option: any;
                          TimePicker: boolean;
                        },
                        index: number,
                      ) => {
                        return item.TimePicker ? (
                          <ProFormDateTimePicker
                            key={index}
                            name={item.name}
                            width='md'
                            label={item.label}
                          />
                        ) : item.isSelect ? (
                          <ProFormSelect
                            key={index}
                            options={item.option}
                            width='md'
                            name={item.name}
                            label={item.label}
                          />
                        ) : (
                          <ProFormText
                            key={index}
                            name={item.name}
                            width='md'
                            disabled={item.disabled}
                            label={item.label}
                            placeholder={item.placeholder || item.label}
                          />
                        );
                      },
                    )}
                  </ProForm.Group>
                ) : (
                  ''
                )}
              </div>
            </div>
          );
        })}
      </DrawerForm>
      <ModalForm
        title={drawerTitle}
        visible={modalVisit}
        formRef={formRef5}
        onFinish={(values) => modalSubmit(values, radioType, choiceData, interworkingData, options)}
        onVisibleChange={setModalVisit}
        modalProps={{ centered: true }}
      >
        {options === 'deploy' ? (
          <Radio.Group onChange={onRadioChange} name='islevel' defaultValue={radioType}>
            <Radio value='1'>普通版(个人)</Radio>
            <Radio value='2'>普通版(企业)</Radio>
            <Radio value='3'>快递版</Radio>
          </Radio.Group>
        ) : options === 'Interworking' ? (
          <div>
            <div>互通小程序名称：{currentData.app_label}</div>
            <Search
              placeholder='输入互通公众号平台标识'
              allowClear
              size='large'
              onSearch={(values) => onSearch(values, currentData, 'officialAccountsName')}
            />
            <div>{interworkingData.nick_name}</div>
          </div>
        ) : (
          ''
        )}
      </ModalForm>
      <DragTable>
        <ProTable<Kbdby>
          className='kb-pro-table'
          actionRef={actionRef}
          pagination={{
            pageSize: 20,
            showQuickJumper: false,
            showSizeChanger: false,
          }}
          request={(values) => fetchTableList(values, searchData)}
          rowKey={(record) => record.id}
          columns={columns}
          search={false}
          scroll={{ x: 1300 }}
          options={false}
          rowSelection={{
            type: 'checkbox',
            onChange: selectiChange,
            getCheckboxProps: (record: any) => ({
              disabled: record.is_newbest == '1',
            }),
          }}
        />
      </DragTable>
    </PageContainer>
  );
};

export default Administrators;
